package com.pine.app.module.security.core.authorize.manager.impl;

import com.google.common.collect.Sets;
import com.pine.app.module.security.core.Authentication;
import com.pine.app.module.security.core.SecurityContextHolder;
import com.pine.app.module.security.core.authorize.manager.MethodAuthorizeDataManager;
import com.pine.app.module.security.core.common.enums.ErrorType;
import com.pine.app.module.security.core.exception.AccessDeniedException;
import com.pine.app.module.security.core.userdetails.User;
import com.pine.app.module.security.oauth.provider.OAuth2ClientRequest;

import java.util.Set;

/**
 * @author xiaoyuan
 * @create 2020/3/13 14:36
 **/

public class DefaultMethodAuthorizeDataManagerImpl implements MethodAuthorizeDataManager {
    @Override
    public Set<String> getResources() {
        Authentication authentication =  SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            ErrorType.ACCESS_DENIED.throwThis(AccessDeniedException::new);
        }
        Object ob = authentication.getPrincipal();
        if (ob == null) {
            ErrorType.ACCESS_DENIED.throwThis(AccessDeniedException::new);
        }
        if(ob instanceof User){
            User user = (User) ob;
            Set<String> resouces =   user.getResources();
            if(resouces==null){
                return Sets.newHashSet();
            }
            return resouces;
        }
        return Sets.newHashSet();
    }

    @Override
    public Set<String> getRoles() {
        Authentication authentication =  SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            ErrorType.ACCESS_DENIED.throwThis(AccessDeniedException::new);
        }
        Object ob = authentication.getPrincipal();
        if (ob == null) {
            ErrorType.ACCESS_DENIED.throwThis(AccessDeniedException::new);
        }
        if(ob instanceof User){
            User user = (User) ob;
            Set<String> roles =   user.getRoles();
            if(roles==null){
                return Sets.newHashSet();
            }
            return roles;
        }
        return Sets.newHashSet();
    }

    @Override
    public Set<String> getScopes() {
        Object ob = SecurityContextHolder.getContext().getAuthentication();
        if (ob == null) {
            ErrorType.ACCESS_DENIED.throwThis(AccessDeniedException::new);
        }
        if(ob instanceof OAuth2ClientRequest){
            OAuth2ClientRequest authentication = (OAuth2ClientRequest) ob;
            Set<String> scope =   authentication.getScope();
            if(scope==null){
                return Sets.newHashSet();
            }
            return scope;
        }
        return Sets.newHashSet();
    }
}
